const formatDocList = async (list) => {
  const regex = /\uFF08([^\uFF09]+)\uFF09/;
  const header = list[0][0];
  let newJson = [];
  list.forEach((arr) => {
    arr.shift();
    let minJson = [];
    arr.forEach((v, i) => {
      if (i >= 0 && v.length > 0) {
        const obj = {};
        v.forEach((str, len) => {
          const match = header[len] && header[len].match(regex);
          if(typeof str != 'string' && str!=null) {
            if (str.length > 0) {
              str = str.map(v => v.text).join('');
            }
          }
          obj[match ? match[1] : header[len]] = str ? str + '' : '';
        });
        obj.zh && minJson.push(obj);
      }
    });
    newJson = newJson.concat(minJson);
  });

  const langList = header
    .map((v) => {
      const match = v ? v.match(regex) : null;
      return match && match[1] != 'zh' ? match[1] : '';
    })
    .filter((v) => v);
  const JsonObj = {};
  langList.filter((v) => {
    JsonObj[v] = {};
  });
  for (const item of newJson) {
    Object.keys(item).forEach((key) => {
      if (JsonObj.hasOwnProperty(key)) {
        const len = 6;
        const zhKey = item.zh.replace(/[\n\r]/g, '');
        let objKey = findOrIncrementKey(JsonObj[key], zhKey, len);
        if (item[key].indexOf('\n') != -1) {
          JsonObj[key][objKey] = item[key].split('\n');
        } else {
          JsonObj[key][objKey] = [item[key]];
        }
      }
    });
  }
  return JsonObj;
};

const findOrIncrementKey = (obj, key, len) => {
  let keyname = key.slice(0, len);
  if (keyname == key) {
    return keyname;
  }
  // 检查键名是否存在
  if (!obj.hasOwnProperty(keyname)) {
    return keyname;
  }

  // // 生成递增后缀的新键名

  const generateNewKey = (base, len) => {
    const newKey = base.slice(0, len);
    if (newKey == base) {
      return newKey;
    }
    return newKey == base || !obj.hasOwnProperty(newKey)
      ? newKey
      : generateNewKey(base, newKey.length + 1);
  };

  return generateNewKey(key, keyname.length + 1);
};

export default formatDocList;
